package org.graduation.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.graduation.common.NoPermissionException;
import org.graduation.feignapi.RBACClient;
import org.graduation.model.common.RBAC.Permissions;
import org.graduation.model.common.ResponseResult;
import org.graduation.model.common.project.ProjectUserTable;
import org.graduation.model.dtos.RBAC.CheckPermissionsDTO;
import org.graduation.project.service.ProjectAndUserService;
import org.graduation.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/project/user")
public class ProjectAndUserController {
    @Autowired
    private RBACClient rbacClient;
    @Autowired
    private Token token;
    @Autowired
    private ProjectAndUserService projectAndUserService;

    @RequestMapping(value = "/{pId}", method = RequestMethod.GET)
    public ResponseResult getUserByProjectId(@PathVariable Long pId, HttpServletRequest request) {
        Permissions permission = Permissions.VIEW_PROJECT;
        int uid = token.getUidByToken(token.getTokenByRequest(request));
        if (!checkPermissions(pId, uid, permission)) {
            throw new NoPermissionException(permission);
        }
        return ResponseResult.success(projectAndUserService.getUsers(pId));
    }

    @GetMapping("/{pid}/exist/{uid}")
    public ResponseResult<Boolean> exist(@PathVariable Long pid, @PathVariable Integer uid) {
        return ResponseResult.success(projectAndUserService.existUserInProject(pid, uid));
    }

    @GetMapping("/list/user/{uid}")
    public ResponseResult<List<ProjectUserTable>> listByUser(@PathVariable Integer uid) {
        LambdaQueryWrapper<ProjectUserTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectUserTable::getUid, uid);
        return ResponseResult.success(projectAndUserService.list(queryWrapper));
    }

    protected boolean checkPermissions(Long pId, Integer uid, Permissions permission) {
        CheckPermissionsDTO dto = new CheckPermissionsDTO(pId, uid, permission);
        return rbacClient.check(dto).getCode() == 200;
    }
}
